﻿using Autodesk.Revit.ApplicationServices;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace RevitServer
{
    [Transaction(TransactionMode.Manual)]
    public class MyRevitServer : IExternalCommand
    {
        Document doc;
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            #region 获取Revit的Application对象和当前的文档对象
            Application revitApp = commandData.Application.Application;
            doc = commandData.Application.ActiveUIDocument.Document;
            #endregion
            #region 在Revit中创建Socket服务器端，监听Cad连接绑定IP地址和端口
            int listenPort = 12345;

            var serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            var localEndPoint = new IPEndPoint(IPAddress.Parse("172.17.128.1"), listenPort);
            try
            {
                serverSocket.Bind(localEndPoint);
                serverSocket.Listen(10);
                TaskDialog.Show("提示：", "等待Cad连接...");
                #endregion
                bool isBreak = true;
                while (isBreak)
                {
                    #region 接收Cad连接，并接收信息数据
                    using (var cadSocket = serverSocket.Accept())
                    {
                        var data = new byte[1024];
                        var receiveBytes = cadSocket.Receive(data);
                        var messageReceived = Encoding.UTF8.GetString(data, 0, receiveBytes);

                        var messageParts = messageReceived.Split(',');

                        #region Point

                        var startList_X = new List<double>();
                        var startList_Y = new List<double>();
                        var endList_X = new List<double>();
                        var endList_Y = new List<double>();



                        // switch (messageParts[0])
                        // {
                        //case "Line":


                        for (int i = 0; i < messageParts.Length / 4; i++)
                        {
                            startList_X.Add(double.Parse(messageParts[0 + i * 4]));
                            startList_Y.Add(double.Parse(messageParts[1 + i * 4]));
                            endList_X.Add(double.Parse(messageParts[2 + i * 4]));
                            endList_Y.Add(double.Parse(messageParts[3 + i * 4]));
                        }


                        #endregion

                        for (int i = 0; i < startList_X.Count; i++)
                        {
                            isBreak = CreateWall(startList_X[i], startList_Y[i], endList_X[i], endList_Y[i]);
                        }
                    }
                    //    break;
                    //default:
                    //    break;
                    //}
                    TaskDialog.Show("提示：", "消息已接收！");
                    #endregion
                }
            }
            catch (Exception ex)
            {

                TaskDialog.Show("Error", ex.Message);
            }
            return Result.Succeeded;
        }
        /// <summary>
        /// 创建墙
        /// </summary>
        /// <param name="startX"></param>
        /// <param name="startY"></param>
        /// <param name="endX"></param>
        /// <param name="endY"></param>
        /// <returns></returns>
        public bool CreateWall(double startX, double startY, double endX, double endY)
        {
            using (var trans = new Transaction(doc, "Connect"))
            {
                //创建墙
                trans.Start();
                var startPoint = new XYZ(startX, startY, 0);
                var endPoint = new XYZ(endX, endY, 0);
                var line = Line.CreateBound(startPoint, endPoint);

                var level = doc.ActiveView.GenLevel;
                var wallTypes = new FilteredElementCollector(doc).OfClass(typeof(WallType)).Cast<WallType>().ToList();
                var wall = Wall.Create(doc, line, level.Id, false);
                foreach (var WallType in wallTypes)
                {
                    if (WallType.Name == "常规 - 200mm")
                    {
                        wall.WallType = WallType;

                        break;
                    }
                }

                //wall.WallType = wallType;
                trans.Commit();

            }
            return false;

        }
    }
}
